package com.inhim.pjhim.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.RadioButton;

import com.google.gson.Gson;
import com.inhim.pjhim.R;
import com.inhim.pjhim.activity.HomeActivity;
import com.inhim.pjhim.adapter.VideoBottomDialogAdapter;
import com.inhim.pjhim.dowloadfile.download.DownloadInfo;
import com.inhim.pjhim.dowloadfile.download.limit.DownloadLimitManager;
import com.inhim.pjhim.dowloadfile.ui.ListActivity;
import com.inhim.pjhim.entity.DownloadAuthor;
import com.inhim.pjhim.entity.ProjectListEntity;
import com.inhim.pjhim.entity.ReaderInfo;
import com.inhim.pjhim.http.MyOkHttpClient;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.utils.PrefUtils;
import com.inhim.pjhim.view.BToast;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;
import org.yczbj.ycrefreshviewlib.inter.OnItemClickListener;
import org.yczbj.ycrefreshviewlib.inter.OnLoadMoreListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Request;


/**
 * Created by hsmacmini on 2018/4/16.
 */

public class MuluFragment extends Fragment {
    private RecyclerView rcyclerView;
    private OnVideoLinear onVideoLinear;
    private int mPageNum = 1;
    private Boolean refresh = true;
    private int totalPage;
    private VideoBottomDialogAdapter readerAttachmentAdapter;
    private Gson gson;
    private Activity mContext;
    private boolean mIsPlay = false;
    private List<ProjectListEntity.List> mProjectListEntitys;
    private int mPlayPosition;
    String vedioName, videoPath;
    private File videoFile;
    private ReaderInfo.Reader readerInfo;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mulu, null);
        mProjectListEntitys = new ArrayList<>();
        gson = new Gson();
        //id= Variable.codeId;
        mContext = getActivity();
        // 初始化控件
        rcyclerView = view.findViewById(R.id.recyclerView);
        /*LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rcyclerView.setLayoutManager(linearLayoutManager);*/
        LinearLayoutManager exceptionLayoutManager = new LinearLayoutManager(getActivity()) {

            @Override
            public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
                try {
                    View view = recycler.getViewForPosition(0);
                    if (view != null) {
                        measureChild(view, widthSpec, heightSpec);
                        //int measuredWidth = View.MeasureSpec.getSize(widthSpec);
                        int measuredHeight = view.getMeasuredHeight();
                        int showHeight = measuredHeight * state.getItemCount();
                        /*if(state.getItemCount() >= 5){
                            showHeight = measuredHeight * 5;
                        }*/
                        setMeasuredDimension(widthSpec, showHeight);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        exceptionLayoutManager.setAutoMeasureEnabled(false);
        rcyclerView.setHasFixedSize(false);
        rcyclerView.setLayoutManager(exceptionLayoutManager);
        rcyclerView.setItemAnimator(new DefaultItemAnimator());
        final int ReaderTypeId = getArguments().getInt("ReaderTypeId");
        int ReaderId = getArguments().getInt("ReaderId");
        readerAttachmentAdapter = new VideoBottomDialogAdapter(getActivity());
        readerAttachmentAdapter.setReaderId(ReaderId);
        rcyclerView.setAdapter(readerAttachmentAdapter);
        readerAttachmentAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (position < 0) {
                    return;
                }
                readerAttachmentAdapter.setReaderId(mProjectListEntitys.get(position).getReaderId());
                readerAttachmentAdapter.notifyDataSetChanged();
                if (onVideoLinear != null) {
                    onVideoLinear.setVidoUrl(mProjectListEntitys.get(position).getReaderId());
                }
            }
        });
        //设置上拉加载更多时布局，以及监听事件
        readerAttachmentAdapter.setMore(R.layout.view_more, new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                //可以做请求下一页操作
                mPageNum++;
                refresh = false;
                //getReaderList(ReaderTypeId);
            }
        });
        readerAttachmentAdapter.setChildOnClickListener(new VideoBottomDialogAdapter.ChildOnClickListener() {
            @Override
            public void onClickCollect(CheckBox radioButton, int position) {
                collectionReader(radioButton, readerAttachmentAdapter.getAllData().get(position).getReaderId());
            }

            @Override
            public void onClickDownload(RadioButton radioButton, int position) {
                List<ProjectListEntity.List> adapterList = readerAttachmentAdapter.getAllData();
                getReaderInfo(adapterList.get(position).getReaderId());
                vedioName = adapterList.get(position).getUrl().substring(adapterList.get(position).getUrl().lastIndexOf("/"));
                videoPath = Urls.getFilePath() + vedioName;
                videoFile = new File(videoPath);
                radioButton.setChecked(videoFile.exists());
            }

        });
       /* rcyclerView.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPageNum = 1;
                refresh = true;
                getReaderList(ReaderTypeId);
            }
        });*/

        getReaderList(ReaderTypeId);
        return view;
    }

    private VideoPlayListener mListener;

    public void setListener(VideoPlayListener listener) {
        mListener = listener;
    }

    public interface VideoPlayListener {

        void lastRadio();

        void nextRadio(int playPosition);
    }

    private void getReaderInfo(int readerId) {
        MyOkHttpClient myOkHttpClient = MyOkHttpClient.getInstance();
        myOkHttpClient.asyncGet(Urls.getReaderInfo(readerId, PrefUtils.getString("token", "")), new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
            }

            @Override
            public void onSuccess(Request request, String result) {
                ReaderInfo readerInfos = gson.fromJson(result, ReaderInfo.class);
                if (readerInfos.getCode() == 000) {
                    readerInfo = readerInfos.getReader();
                    dowload(result);
                }
            }
        });
    }

    private void rxPermissionWriteAndRead(String results) {
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                Activity context=getActivity();
                if(context==null){
                    return;
                }
                if (context.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    context.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                } else {
                    List<DownloadInfo> person = null;
                    //查找当前url文件是否正在下载中
                    try {
                        person = LitePal.where("url = ?", readerInfo.getUrl()).find(DownloadInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (videoFile != null && videoFile.exists()) {
                        BToast.showText("您已下载该视频");
                    } else if ((person != null && person.size() > 0)) {
                    /*Intent intent = new Intent(mContext, ListActivity.class);
                    startActivity(intent);*/
                        //DownloadLimitManager.getInstance().download(readerInfo.getUrl());
                        BToast.showText("视频正在下载中");
                    } else {
                        try {
                            JSONObject jsonObject = new JSONObject(results);
                            DownloadInfo businessInfo = gson.fromJson(jsonObject.getJSONObject("reader").toString(), DownloadInfo.class);
                            businessInfo.setFilePath(videoPath);
                            businessInfo.setProgress(0);
                            businessInfo.setProgressText("0");
                            businessInfo.setFileName(businessInfo.getUrl().substring(businessInfo.getUrl().lastIndexOf("/")));
                            businessInfo.setDownloadStatus("download");
                            boolean istrue = businessInfo.save();
                            DownloadAuthor saveAuthor = new DownloadAuthor();
                            saveAuthor.setReaderId(readerInfo.getReaderId());
                            if (readerInfo.getAuthor() != null) {
                                saveAuthor.setArea(readerInfo.getAuthor().getArea());
                                saveAuthor.setCreateTime(readerInfo.getAuthor().getCreateTime());
                                saveAuthor.setHeadPortrait(readerInfo.getAuthor().getHeadPortrait());
                                saveAuthor.setId(readerInfo.getAuthor().getId());
                                saveAuthor.setIdentity(readerInfo.getAuthor().getIdentity());
                                saveAuthor.setName(readerInfo.getAuthor().getName());
                                saveAuthor.setSynopsis(readerInfo.getAuthor().getSynopsis());
                            }
                            saveAuthor.save();
                            if (istrue) {
                            /*Intent intent = new Intent(mContext, ListActivity.class);
                            startActivity(intent);*/
                                DownloadLimitManager.getInstance().download(businessInfo.getUrl());
                                DownloadLimitManager.getInstance().setTitle(businessInfo.getTitle());
                            } else {
                                BToast.showText("下载失败");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
       /* RxPermissions rxPermissions = new RxPermissions(HomeActivity.this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(granted -> {
            if (granted) {
            } else {
                BToast.showText("读写权限被拒绝",true);
            }
        });*/
    }

    private void dowload(String results) {
        rxPermissionWriteAndRead(results);
       /* RxPermissions rxPermissions = new RxPermissions(mContext);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(granted -> {
            if (granted) {
                List<DownloadInfo> person = null;
                //查找当前url文件是否正在下载中
                try {
                    person = LitePal.where("url = ?", readerInfo.getUrl()).find(DownloadInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (videoFile != null && videoFile.exists()) {
                    BToast.showText("您已下载该视频");
                } else if ((person != null && person.size() > 0)) {
                    *//*Intent intent = new Intent(mContext, ListActivity.class);
                    startActivity(intent);*//*
                    //DownloadLimitManager.getInstance().download(readerInfo.getUrl());
                    BToast.showText("视频正在下载中");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(results);
                        DownloadInfo businessInfo = gson.fromJson(jsonObject.getJSONObject("reader").toString(), DownloadInfo.class);
                        businessInfo.setFilePath(videoPath);
                        businessInfo.setProgress(0);
                        businessInfo.setProgressText("0");
                        businessInfo.setFileName(businessInfo.getUrl().substring(businessInfo.getUrl().lastIndexOf("/")));
                        businessInfo.setDownloadStatus("download");
                        boolean istrue = businessInfo.save();
                        DownloadAuthor saveAuthor = new DownloadAuthor();
                        saveAuthor.setReaderId(readerInfo.getReaderId());
                        if (readerInfo.getAuthor() != null) {
                            saveAuthor.setArea(readerInfo.getAuthor().getArea());
                            saveAuthor.setCreateTime(readerInfo.getAuthor().getCreateTime());
                            saveAuthor.setHeadPortrait(readerInfo.getAuthor().getHeadPortrait());
                            saveAuthor.setId(readerInfo.getAuthor().getId());
                            saveAuthor.setIdentity(readerInfo.getAuthor().getIdentity());
                            saveAuthor.setName(readerInfo.getAuthor().getName());
                            saveAuthor.setSynopsis(readerInfo.getAuthor().getSynopsis());
                        }
                        saveAuthor.save();
                        if (istrue) {
                            *//*Intent intent = new Intent(mContext, ListActivity.class);
                            startActivity(intent);*//*
                            DownloadLimitManager.getInstance().download(businessInfo.getUrl());
                            DownloadLimitManager.getInstance().setTitle(businessInfo.getTitle());
                        } else {
                            BToast.showText("下载失败");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                BToast.showText("读写权限被拒绝", true);
            }
        });*/

    }


    private void collectionReader(CheckBox mCheckBox, int readerId) {
        MyOkHttpClient myOkHttpClient = MyOkHttpClient.getInstance();
        myOkHttpClient.asyncJsonPost(Urls.collectionReader(readerId), new HashMap(),
                new MyOkHttpClient.HttpCallBack() {
                    @Override
                    public void onError(Request request, IOException e) {
                        if (mCheckBox.isChecked()) {
                            mCheckBox.setChecked(false);
                        } else {
                            mCheckBox.setChecked(true);
                        }
                    }

                    @Override
                    public void onSuccess(Request request, String result) {
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if (jsonObject.getInt("code") != 0) {
                                BToast.showText(jsonObject.getString("msg"), false);
                                //收藏失败时将按钮状态还原
                                if (mCheckBox.isChecked()) {
                                    mCheckBox.setChecked(false);
                                } else {
                                    mCheckBox.setChecked(true);
                                }
                            } else {
                                if (mCheckBox.isChecked()) {
                                    BToast.showText("收藏成功", true);
                                } else {
                                    BToast.showText("已取消收藏", true);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    private void getReaderList(int ReaderTypeId) {
        /** {
         * 获取系列专题文章
         }*/
        HashMap postMap = new HashMap();
        postMap.put("readerTypeId", ReaderTypeId);
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(Urls.getReaderList(mPageNum, 50, "asc"), postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {

            }

            @Override
            public void onSuccess(Request request, String result) {
                Gson gson = new Gson();
                ProjectListEntity readerList = gson.fromJson(result, ProjectListEntity.class);
                if (readerList.getCode() == 0) {
                    totalPage = readerList.getPage().getTotalPage();
                    if (refresh) {
                        readerAttachmentAdapter.clear();
                        mProjectListEntitys.clear();
                    }
                    readerAttachmentAdapter.addAll(readerList.getPage().getList());
                    mProjectListEntitys.addAll(readerList.getPage().getList());
                    if (mPageNum >= totalPage) {
                        readerAttachmentAdapter.pauseMore();
                    }
                } else {
                    BToast.showText(readerList.getMsg(), false);
                }
                readerAttachmentAdapter.notifyDataSetChanged();
            }
        });
    }


    public void setvedioLinear(OnVideoLinear onVideoLinear) {
        this.onVideoLinear = onVideoLinear;
    }

    public interface OnVideoLinear {
        void setVidoUrl(int ReaderId);
    }
}
